#include "screenviewer.h"
#include <QDebug>
#include <QHostAddress>

ScreenViewer::ScreenViewer(QObject *parent) : QObject(parent),
    udpSocket(nullptr), displayLabel(nullptr), isListeningFlag(false), frameCounter(0)
{
}

ScreenViewer::~ScreenViewer()
{
    if (isListeningFlag) {
        stopListening();
    }
    
    if (udpSocket) {
        udpSocket->deleteLater();
    }
}

bool ScreenViewer::initialize()
{
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, &QUdpSocket::readyRead, this, &ScreenViewer::onReadyRead);
    connect(udpSocket, &QUdpSocket::errorOccurred, this, &ScreenViewer::onSocketError);
    
    qDebug() << "屏幕查看器初始化完成";
    return true;
}

void ScreenViewer::startListening(int port)
{
    if (isListeningFlag) {
        return;
    }
    
    if (!udpSocket->bind(QHostAddress::Any, port)) {
        emit errorOccurred(QString("无法绑定端口 %1").arg(port));
        return;
    }
    
    qDebug() << "开始监听屏幕数据，端口:" << port;
    
    isListeningFlag = true;
    frameCounter = 0;
    
    emit listeningStarted();
}

void ScreenViewer::stopListening()
{
    if (!isListeningFlag) {
        return;
    }
    
    qDebug() << "停止监听屏幕数据";
    
    udpSocket->close();
    isListeningFlag = false;
    
    emit listeningStopped();
}

bool ScreenViewer::isListening() const
{
    return isListeningFlag;
}

void ScreenViewer::setDisplayLabel(QLabel* label)
{
    displayLabel = label;
}

void ScreenViewer::onReadyRead()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        
        // 解码图像数据
        QPixmap screen;
        if (screen.loadFromData(datagram, "JPEG")) {
            emit screenReceived(screen);
            
            // 更新显示
            if (displayLabel) {
                displayLabel->setPixmap(screen.scaled(displayLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
            }
            
            frameCounter++;
            if (frameCounter % 25 == 0) {
                qDebug() << "屏幕查看器: 已接收" << frameCounter << "帧";
            }
        } else {
            emit errorOccurred("图像数据解码失败");
        }
    }
}

void ScreenViewer::onSocketError(QAbstractSocket::SocketError error)
{
    QString errorStr = QString("UDP Socket错误: %1").arg(udpSocket->errorString());
    emit errorOccurred(errorStr);
}
